package study.线程池.completableFuture;

import study.线程池.Task;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author 刘伟涛
 * @Date 2023/12/5 15:47
 **/
public class Demo {
    public static void main(String[] args) {
        List<CompletableFuture<Long>> submitList = new ArrayList<>();
        System.out.println("执行子任务前：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
        for (int i = 1; i <= 8; i++){
            //submit方法再执行的过程Task任务就异步开始调用。
            submitList.add(CompletableFuture.supplyAsync(()->{
                try {
                    return new Task().call();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }));
            System.out.println("(" + i + ")执行了submit方法");
        }
        try {
            //主线程等待6秒
            BigDecimal second = new BigDecimal("6");
            Thread.sleep(second.multiply(new BigDecimal("1000")).longValue());
            System.out.println("等待了" + second + "秒");
            int i = 1;
            for (CompletableFuture<Long> submit : submitList) {
                System.out.println("(" + i++ + ")now：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
                System.out.println("submit：" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(submit.get())));
                System.out.println("执行结束：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
            }
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
